package com.luck.global;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ServiceLoaderUtil;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class TraceIdGlobalFilter implements GlobalFilter {
    private static final String TRACE_ID = "traceId";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String traceId = request.getHeaders().getFirst(TRACE_ID);
        if (ObjectUtil.isNotEmpty(traceId)){
            return chain.filter(exchange);
        }
        traceId = IdUtil.simpleUUID();
        MDC.put(TRACE_ID,traceId);
        ServerHttpRequest request2 = request.mutate().header(TRACE_ID, traceId).build();
        ServerWebExchange exchange2 = exchange.mutate().request(request2).build();
        log.debug("traceId:{}",traceId);
        return chain.filter(exchange2);
    }
}
